<?php

namespace App\Http\Model;

use Illuminate\Database\Eloquent\Model;

class Categroy extends Model
{
    protected $table = 'categroy';
    protected $primaryKey = 'cat_id';
    public $timestamps = false;
    protected $guarded = [];

    /**
     * @param $cate 无限极分类
     * @param int $parent_id
     * @param int $level
     * @param string $html
     * @return array
     */
    public function getTree($cate, $parent_id = 0, $level = 0, $html = '--')
    {
        $tree = array();
        foreach ($cate as $v) {
            if ($v->parent_id == $parent_id) {
                $v->level = $level + 1;
                $v->html = str_repeat($html, $level);
                $tree[] = $v;
                //print_r($tree);
                $tree = array_merge($tree, $this->getTree($cate, $v->cat_id, $level + 1, $html));
            }
        }
        return $tree;
    }

    /**
     * 检测栏目pid是否是自身栏目树id
     * @param array $data post数据集合
     * @param int $cid 栏目自身id
     * @return bool
     */
    public function checkId($data,$cid)
    {
        $pid = $data['parent_id'];
        //获取所有栏目集合
        $cat_list = Categroy::all();
        //获取栏目下的子栏目树
        $list = $this->getTree($cat_list, $cid);
        //1.返回空数组
        if(!$list){
            return false;
        }
        //2.所有子栏目的catid
        foreach($list as $cat){
            if($cat->cat_id == $pid){
                return true;
            }
        }
        //返回
        return false;
    }

    /**
     * 获取首页所有栏目数据
     */
    public function getIndexCate(){
        /**1.获取所有顶级栏目*/
        $top_list = $this -> where('parent_id',0)->get();
        /**2.为所有顶级栏目分配二级栏目*/
        foreach($top_list as $key => $top_cat){
            $top_list[$key]->second_cat = $this -> getSingleCate($top_cat->cat_id);
            /**3.为所有二级栏目分配三级栏目数据*/
            foreach($top_list[$key]->second_cat as $k => $second_cat){
                $temp = $top_list[$key]->second_cat;
                $temp[$k]->third_cat = $this -> getSingleCate($second_cat->cat_id);
            }
        }
        /**4.返回遍历数据*/
        return $top_list;
    }

    /**
     * 获取单栏目二级数据
     * @param int $cid 栏目id
     */
    private function getSingleCate($cid){
        /**获取所有栏目集合*/
        $all = $this -> where('parent_id','!=',0)->get();
        $temp = [];
        foreach($all as $key => $cat){
            if($cat->parent_id == $cid){
                $temp[] = $cat;
            }
        }
        return $temp;
    }
};

